<?php

namespace Biz\service\Album;

use hhz\constant\redis\redisKeys;
use Hhz\Redis\newCache;
use Hhz\Redis\otherRedis;
use Biz\model\Album\AlbumListModel;
use Biz\model\Album\AlbumRelateTagsModel;
use Biz\model\Album\AlbumWikiListModel;
use Biz\model\ShopFavorite as mShopFavorite;
use Biz\model\wiki\WikiBuyModel;
use Biz\model\wiki\WikiList;
use Biz\module\Classes\wiki\RelateWiki;
use Biz\module\Classes\wiki\Wiki as clsWiki;
use Doraemon\amqp\CommunityQueue;
use Doraemon\cache\AlbumCounter;
use Doraemon\cache\UserCounter;
use Doraemon\model\Favorite as mFavorite;
use Doraemon\model\Like as mLike;
use Doraemon\model\Member;
use Doraemon\model\NewTag\PackageApplication;
use Doraemon\model\NewTag\TagPackage;
use Doraemon\model\Photos as DbPhotos;
use Doraemon\model\Sysmsg;
use Doraemon\pockets\IdSender\IdSender;
use Doraemon\service\Favorite;
use Doraemon\service\Follow;
use Doraemon\service\Like;
use Doraemon\service\Like as sLike;
use Doraemon\service\statSign\Basic as basicStatSign;
use Doraemon\service\User;
use Doraemon\tools\BlockType;
use Doraemon\tools\ExposeLog;
use Doraemon\tools\HhzClient;
use Doraemon\tools\HhzClient as tHhzClient;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\IdParse;
use Doraemon\tools\Log;
use Doraemon\tools\PointConfig;
use Doraemon\tools\Sort;
use Exception;


class AlbumListService
{

    const PAGESIZE = 20;

    /**
     * @param $albumId
     * @return array
     */
    public static function getAlbumInfo($albumId): array
    {
        $data = AlbumListModel::getByWhere(['album_id' => $albumId]);
        if ($data) {
            $tagList = AlbumRelateTagsModel::selectByWhere([
                'status' => AlbumRelateTagsModel::STATUS_NORMAL,
                'album_id' => $albumId,
            ]);
            $tags = [];
            if ($tagList) {
                foreach ($tagList as $item) {
                    $tags[] = $item['package_name'] . '|' . $item['tag_name'];
                }
            }
            $data['publish_time_int'] = $data['publish_time'];
            $data['publish_time'] = $data['publish_time_string'];
            $data['tag_list'] = $tags;
            $wikiList = AlbumWikiListModel::selectByWhere([
                'album_id' => $albumId,
                'status' => AlbumWikiListModel::STATUS_NORMAL,
                'ORDER' => ['sort' => 'ASC', 'addtime' => 'DESC']
            ]);
            $wikiIdArr = array_column($wikiList, 'wiki_id');
            $wikiInfoMap = clsWiki::getWikiBaseInfos($wikiIdArr);
            $wiki = [];
            if ($wikiList) {
                foreach ($wikiList as $value) {
                    if ($value['obj_id'] && empty($value['content'])) {
                        $value['content'] = DbPhotos::getPhoto($value['obj_id'])['remark'] ?? '';
                    }
                    $value['goods_name'] = $wikiInfoMap[$value['wiki_id']]['simple_title'] ?: $wikiInfoMap[$value['wiki_id']]['title'];
                    $wiki[] = $value;
                }
            }
            $data['wiki_list'] = $wiki;
        }

        return $data;
    }

    /**
     * @param $albumId
     * @param int $type
     * @return array
     * @throws \Exception
     */
    public static function getInfo($albumId, int $type = 1): array
    {
        $data = AlbumListModel::getByWhere(['album_id' => $albumId, 'status[!]' => AlbumListModel::STATUS_DELETE], ['title', 'desc', 'cover_img', 'status', 'uid', 'album_id']);
        if (empty($data)) {
            throw new Exception('清单不存在');
        }
        if ($type == 2) {
            $wikis = WikiListService::getGoodsList($albumId, 1) ?? [];
            $data['goods_list'] = $wikis;
        }

        return $data;
    }

    /**
     * pgc 新增或修改清单
     * @param $data
     * @param $albumId
     * @return bool
     * @throws \Exception
     */
    public static function saveAlbumData($data, $albumId): bool
    {
        $uid = $data['uid'] ?? 0;
        $adminId = $data['admin_id'] ?? 0;
        if ($uid == 0) {
            throw new \Exception('参数不合法，必须指定用户');
        }
        $tagList = $data['tag_list'];
        $tags = [];
        if ($tagList) {
            foreach ($tagList as $item) {
                $tags[] = explode('|', $item)[1];
            }
        }
        if ($data['publish_time'] > 0) { //设置了发布时间 并且发布时间大于当前时间 状态为待发布 （比如 未到发布时间时  对发布时间进行了修改 则要更新定时发布时间）
            if ($data['publish_time'] < time()) {
                throw new \Exception('发布时间必须大于当前时间');
            }
            $status = AlbumListModel::STATUS_DRAFT;
        } else {
            $status = AlbumListModel::STATUS_SUCCESS;
        }
        $albumData = [
            'uid' => $uid,
            'title' => $data['title'],
            'desc' => $data['desc'],
            'cover_img' => $data['cover_img'],
            'publish_time' => $data['publish_time'],
            'tags' => implode(',', $tags),
            'admin_id' => $adminId,
            'status' => $status,
            'wiki_count' => count($data['wiki_list']),
        ];

        if (!empty($albumId)) { //更新操作
            if ($data['publish_time'] == 0) { //更新时  假如已过发布时间 则不用更新此字段
                unset($albumData['publish_time']);
            }
            unset($albumData['uid']);
            $result = AlbumListModel::updateDataByWhere($albumData, ['album_id' => $albumId]);
        } else {//添加操作
            $albumId = IdSender::getAlbumId($uid);

            //创建清单
            if ($data['publish_time'] == 0) { //创建清单时 假如没有选择发布时间 则发布时间取当前时间戳
                $albumData['publish_time'] = time();
            }
            $result = AlbumListModel::insertData(array_merge($albumData, ['album_id' => $albumId]));
            AlbumCounter::increaseAlbumCounter($albumId, AlbumCounter::ACT_READ, rand(68, 100));
        }

        //关联清单商品以及标签
        if ($result) {
            AlbumWikiListService::saveAlbumWikiList($data['wiki_list'], $albumId, $data['title'], $uid);
            AlbumTagListService::saveAlbumTagList($albumId, $tagList, $adminId);

            if ($data['publish_time'] > 0 && $albumId) { //设置了发布时间 放入定时发布缓存中
                $key = redisKeys::KEY_B_OTHER_ALBUM_TIME_PUBLISH;
                $redis = new otherRedis($key);
                $redis->zadd($key, [$albumId => $data['publish_time']]);
//                AlbumTimePublishCache::setAlbumTimePublish($albumId, $data['publish_time']);
            }
            AlbumListService::setTopcCache();
            return true;
        } else {
            return false;
        }

    }

    /**
     * ugc 用户创建清单
     * @param $data
     * @param $albumId
     * @return mixed|string
     */
    public static function addOrUpdateAlbum($data, $albumId)
    {
        $uid = $data['uid'];
        $wikiList = $data['wiki_list'];
        $albumData = [
            'uid' => $uid,
            'title' => $data['title'],
            'status' => $data['status'],
            'wiki_count' => count($wikiList),
        ];
        if (empty($albumId)) { //添加操作
            $albumId = IdSender::getAlbumId($uid);
            //获取自增清单id
            $albumData['album_id'] = $albumId;
            //ugc添加清单 发布时间默认取当前时间
            $albumData['publish_time'] = time();
            //ugc创建清单时 默认第一张商品图为封面图
            $firstWikiId = $wikiList[0]['wiki_id'];
            $wikiInfo = clsWiki::getWikiBaseInfos([$firstWikiId]);
            $coverImg = $wikiInfo[$firstWikiId]['cover_img'] ?? '';
            $albumData['cover_img'] = $coverImg;
            $result = AlbumListModel::insertData($albumData);

            //创建清单加积分
            CommunityQueue::insertQueue(PointConfig::MQ_QUEUE_URL, [
                'event_name' => PointConfig::POINT_DETAILED_LIST,
                'obj_id' => $albumId,//创建清单的id
                'uid' => $uid,//用户的uid
                'type' => PointConfig::POINT_AWARD,
            ], CommunityQueue::QUEUE_COMMUNITY);
        } else {//更新操作
            //查询清单状态
            $albumStatus = AlbumListModel::getByWhere(['album_id' => $albumId], 'status');
            //用户发布完清单 且审核通过、或是待复审 再次编辑 则为待复审状态
            if (AlbumListModel::STATUS_SUCCESS == $albumStatus || AlbumListModel::STATUS_WAIT_CHECK == $albumStatus) {
                $albumData['status'] = AlbumListModel::STATUS_WAIT_CHECK;
                //待复审状态 要把分数和质量恢复到默认值
//                $albumData['score'] = 0;
//                $albumData['quality'] = 0;
            }
            //如果用户发布清单时设置为了私密 则修改为公开时  需要把发布时间改为公开时间
            if (AlbumListModel::STATUS_USER_PRIVATE == $albumStatus && AlbumListModel::STATUS_UNTREATED == $albumData['status']) {
                $albumData['publish_time'] = time();
            }
            $result = AlbumListModel::updateDataByWhere($albumData, ['album_id' => $albumId]);
        }
        if ($result) {
            //关联清单商品
            AlbumWikiListService::saveAlbumWikiList($wikiList, $albumId, $data['title'], $uid);
        }

        return $albumId;

    }

    /**
     * @param $uid
     * @param $currUid
     * @param $page
     * @param $pageSize
     * @return array
     */
    public static function getSelfBuiltList($uid, $currUid, $page, $pageSize): array
    {
        if ($uid == $currUid) {//查看自己的
            $where['status[!]'] = AlbumListModel::STATUS_DELETE;
            $where['uid'] = $currUid;
        } else { //查看别人的
            $where['status'] = AlbumListModel::STATS_PUBLIC_SHOW_MAP;
            $where['uid'] = $uid;
        }
        $total = AlbumListModel::count($where);
        $where['LIMIT'] = [($page - 1) * $pageSize, $pageSize];
        $where['ORDER'] = ['edittime' => 'DESC'];
        $list = AlbumListModel::selectByWhere($where);
        $isOver = count($list) < $pageSize ? 1 : 0;
        return [$list,$total,$isOver];
    }

    /**
     * @param $uid
     * @param $currUid
     * @return array
     */
    public static function getHomePageHead($uid, $currUid): array
    {
        //1、查询自建清单数量 区分自己以及看别人的

        if ($uid == $currUid) {//查看自己的
            $where['status[!]'] = AlbumListModel::STATUS_DELETE;
            $where['uid'] = $currUid;
        } else { //查看别人的
            $where['status'] = AlbumListModel::STATS_PUBLIC_SHOW_MAP;
            $where['uid'] = $uid;
        }
        $result['album_self_total'] = AlbumListModel::count($where);

        //2、查询收藏清单数量
        $result['album_fav_total'] = Favorite::getCountByType($uid, mFavorite::TYPE_WIKI_ALBUM);

        //3、从计数器 查询关联过、想买、买过数量

        $counter = UserCounter::getOne($uid);
        $result['relate_wiki_counter'] = (int)$counter['relate_wiki'];
        $result['fav_spu_counter'] = (int)$counter['fav_spu'];
        $result['buy_spu_counter'] = (int)$counter['buy_spu'];

        //4、查询最新的商品封面图
        $relateWikiId = WikiList::getUserWikiList($uid, [0, 1], ['addtime' => 'DESC', 'id' => 'DESC'])[0]['wiki_id'] ?? 0;
        $buyWikiId = WikiBuyModel::getByUid(['uid' => $uid, 'status' => WikiBuyModel::STATUS_NORMAL, 'ORDER' => ['edittime' => 'DESC']], 'wiki_id') ?? 0;
        $favWikiId = mShopFavorite::getFavInfos($uid, mShopFavorite::TYPE_WIKI, mShopFavorite::APP_SOURCE_APP, 1, 1)['list'][0]['obj_id'] ?? 0;

        $wikiInfo = clsWiki::getWikiBaseInfos([$buyWikiId, $favWikiId, $relateWikiId]);

        $result['relate_wiki_img_url'] = $wikiInfo[$relateWikiId]['cover_img'] ?? '';
        $result['relate_wiki_id'] = $relateWikiId ?? 0;
        $result['fav_spu_img_url'] = $wikiInfo[$favWikiId]['cover_img'] ?? '';
        $result['fav_spu_wiki_id'] = $favWikiId ?? 0;
        $result['buy_spu_img_url'] = $wikiInfo[$buyWikiId]['cover_img'] ?? '';
        $result['buy_spu_wiki_id'] = $buyWikiId ?? 0;

        //查看是否有创建清单的权限
        $result['is_can_built_album'] = AlbumListService::checkIsCanBuiltAlbum($uid);
        return $result;
    }

    /**
     * @param $albumId
     * @param $uid
     * @param int $adminId
     * @return bool
     * @throws \Exception
     */
    public static function delAlbum($albumId, $uid, $adminId = 0)
    {
        //这里要提前查询清单基本信息 更新用户成长值需要
        $albumInfo = self::getAlbumListCache([$albumId])[$albumId] ?? [];
        //这里要提前查询清单商品信息 更新用户成长值需要
        $wikiIds = AlbumWikiListModel::selectByWhere(['album_id'=>$albumId,'status'=>AlbumWikiListModel::STATUS_NORMAL],'wiki_id');

        //1、删除清单
        AlbumListModel::updateDataByWhere(['status' => AlbumListModel::STATUS_DELETE, 'admin_id' => $adminId],
            ['album_id' => $albumId, 'uid' => $uid]);

        //2、删除清单商品
        AlbumWikiListService::delAlbumWikiList($albumId, $uid);

        //3、删除标签关联关系
        AlbumTagListService::delAlbumRelateTags($albumId, $adminId);
        //4、收藏清单计数器修改
        $likeCount = sLike::delLikeByObjId($albumId, mLike::LIKE_TYPE_WIKI_ALBUM);
        Log::debug('delAlbum', ['like_count' => $likeCount]);
        if ($likeCount) {
            //扣除当前清单的点赞数
            UserCounter::decreaseUserCounter($uid, UserCounter::TYPE_BELIKED, -$likeCount);
        }

        $favoriteCount = Favorite::delFavoriteByObjId($albumId, mLike::LIKE_TYPE_WIKI_ALBUM);
        Log::debug('delAlbum-favorite', ['$album_id' => $albumId, '$favorite_count' => $favoriteCount]);

        if ($favoriteCount) {
            //扣除当前清单的收藏数
            UserCounter::decreaseUserCounter($uid, UserCounter::TYPE_BEFAVED, -$favoriteCount);
        }
        //更新用户成长值
        $remarks = ['old_quality' => 0, 'new_quality' => $albumInfo['quality'] ?? 0, 'new_wiki_id' => $wikiIds,'old_wiki_id' => []];
        \Doraemon\amqp\CommunityQueue::insertQueue(\Doraemon\tools\Creator\GrowthConfig::MQ_QUEUE_URL, [
            'event_name' => \Doraemon\tools\Creator\GrowthConfig::GROWTH_ALBUM_LIST_DEL,
            'obj_id' => $albumId,
            'uid' => $uid,
            'remarks' => json_encode($remarks, JSON_UNESCAPED_UNICODE),
        ], \Doraemon\amqp\CommunityQueue::QUEUE_COMMUNITY);


        return true;


    }

    /**
     * 查询符合条件的标签列表
     * @param array $where
     * @return array
     */
    public static function getTagList(array $where = []): array
    {
        //查询 标签包 用户为好物清单的id
        $applicationId = PackageApplication::getInfoByName(AlbumListModel::TAG_APPLICATION_NAME, 'id');
        if (!$applicationId) {
            return [];
        }
        if (empty($where)) {
            $tagArr = TagPackage::getInfosByCondition(['application_id' => $applicationId]);
        } else {
            $tagArr = TagPackage::getInfosByCondition(array_merge(['application_id' => $applicationId], $where));
        }
        $tagList = [];

        if ($tagArr) {
            foreach ($tagArr as $tagInfo) {
                if ($tagInfo['tags']) {
                    $tags = explode(",", $tagInfo['tags']);
                    foreach ($tags as $tag) {
                        $tagList[] = $tagInfo['description'] . '|' . $tag;
                    }
                }

            }
        }

        return $tagList;
    }

    public static function getAlbumByAlbumId($album_id)
    {
        $result = [];
        $albumInfo = AlbumListModel::getByWhere(['album_id' => $album_id]);
        if ($albumInfo && is_array($albumInfo)) {
            $albumCounter = AlbumCounter::getOne($album_id);
            $read = $albumCounter['read'];
            $read = $read >= 3 ? 3 : $read;
            $avatar_list = array_column(clsWiki::getRandUserCoverImg($read), 'cover_img');
            if (in_array($albumInfo['status'], [AlbumListModel::STATUS_PRIVATE, AlbumListModel::STATUS_USER_PRIVATE])) {
                $albumCounter['read'] = 0;
                $avatar_list = [];
            }
            $result = [
                'album_id' => $albumInfo['album_id'],
                'title' => $albumInfo['title'],
                'desc' => $albumInfo['desc'],
                'status' => $albumInfo['status'],
                'cover_img_url' => $albumInfo['cover_img'],
                'joiner_num' => $albumCounter['read'] ?: 0,
                'is_like' => Like::isLike(tHhzClient::getUid(), $album_id, 9),//是否点赞了
                'is_favorite' => Favorite::isFavorite(tHhzClient::getUid(), $album_id, mFavorite::TYPE_WIKI_ALBUM),
                'avatar_list' => $avatar_list ?: array_slice([
                    "https://img.haohaozhu.cn/Pic-imageShow/sq_270/0004hn7b?iv=1&v=3",
                    "https://img.haohaozhu.cn/Pic-imageShow/sq_270/0004hn7p?iv=1&v=2",
                    "https://img.haohaozhu.cn/Pic-imageShow/sq_270/0004hneg?iv=1&v=3"], 0, $read),
                'counter' => [
                    'like_num' => $albumCounter['like'] ?: 0,
                    'comment' => $albumCounter['comment'] ?: 0,
                    'favorite' => $albumCounter['favorite'] ?: 0
                ],
                'is_created' => $albumInfo['publish_time'] >= strtotime($albumInfo['edittime']) ? true : false,
                "show_time" => $albumInfo['publish_time'] >= strtotime($albumInfo['edittime']) ? $albumInfo['publish_time'] : strtotime($albumInfo['edittime']),
            ];
            //非官方清单展示
            $result['user_info'] = User::getUserInfo($albumInfo['uid'], true, HhzClient::getUid());
            $result['is_can_edit'] = false;
            $result['is_can_delete'] = false;
            if (HhzClient::getUid() == $albumInfo['uid']) {
                $result['is_can_edit'] = true;
                $newRedis = new newCache(redisKeys::KEY_B_CACHE_ALBUM_RECOMMEND_OFFICIAL_LIST);
                $aData = $newRedis->getCache();
                $recommALbumIds = $aData ? explode(',', $aData) : [];
                if (!in_array($album_id, $recommALbumIds)) {
                    $result['is_can_delete'] = true;
                }
            }
            $result['is_official'] = in_array($albumInfo['uid'], AlbumListModel::DEFAULT_UID_HAOHAOZHU) ? 1 : 0;;
        }

        return $result;

    }


    public static function getMoreAlbum($page = 1)
    {
        $result = [];
        $list = AlbumListModel::selectByWhere([
                'LIMIT' => [($page - 1) * self::PAGESIZE, self::PAGESIZE],
                'status' => AlbumListModel::STATS_LIST_PUBLIC_SHOW_MAP,
                'score[>=]' => AlbumListModel::SCORE_GOOD,
//                'uid' => AlbumListModel::getDefaultUid(),
                'ORDER' => ['publish_time' => 'DESC'],
            ]
        );
        if ($list && is_array($list)) {
            $formateInfo = self::formatAlbums($list);
            $albumIds = array_column($list, 'album_id');
            $albumCounters = AlbumCounter::getMulti($albumIds);
            foreach ($formateInfo as $key => $val) {
                $val['statSign'] = basicStatSign::genStatSign(basicStatSign::ALBUM_LIST_PAGE_ALBUM_LIST, [
                    basicStatSign::EXTEND_KEY_OBJ_TYPE => BlockType::TYPE_WIKI_ALBUM,
                    basicStatSign::EXTEND_KEY_OBJ_ID => $val['album_info']['album_id'],
                    basicStatSign::EXTEND_KEY_POS => 'order_general',
                    basicStatSign::EXTEND_KEY_INDEX => $key,
                ], []);
                $val['album_info']['joiner_num'] = $albumCounters[$val['album_info']['album_id']]['read'] ?: 0;

                $result[] = $val;
            }
        }

        return $result;
    }

    /**
     * @param $albumInfos
     * @return array
     */
    public static function formatAlbums($albumInfos)
    {
        $result = [];
        if ($albumInfos && is_array($albumInfos)) {
            foreach ($albumInfos as $val) {
                $result[] = [
                    'type' => BlockType::TYPE_WIKI_ALBUM,
                    'album_info' => [
                        'album_id' => $val['album_id'],
                        'title' => $val['title'],
                        'desc' => $val['desc'],
                        'cover_img_url' => $val['cover_img'],
                        'quality' => $val['quality'],
                    ],

                ];
            }
        }

        return $result;
    }


    public static function getRelaAlbumByAlbumId($album_id)
    {
        $album_infos = AlbumRelateTagsModel::selectByWhere([
            'album_id' => $album_id,
            'status' => AlbumRelateTagsModel::STATUS_NORMAL
        ], ['package_name', 'tag_name']);
        $relaInfo = [];
        $notAlbumIds = [$album_id];
        if ($album_infos && is_array($album_infos)) {
            $packageName = array_column($album_infos, 'package_name');
            $tagName = array_column($album_infos, 'tag_name');
            $albumImfo = AlbumRelateTagsModel::getRelaAlbumByWhere([
                'tag_name' => $tagName,
                'package_name' => $packageName,
                'not_album_ids' => $notAlbumIds,
                'limit' => 30,
            ]);
            $albumInfo = array_combine(array_column($albumImfo, 'album_id'), $albumImfo);
            $albumInfo = array_slice($albumInfo, 0, 6);
            $relaInfo = $albumInfo;
            if (count($relaInfo) < 6) {
                if ($relaInfo && is_array($relaInfo)) {
                    $album_ids = array_column($relaInfo, 'album_id');
                    $notAlbumIds = array_merge($notAlbumIds, $album_ids);
                }
                $albumImfo = AlbumRelateTagsModel::getRelaAlbumByWhere([
                    'package_name' => $packageName,
                    'not_album_ids' => $notAlbumIds,
                    'limit' => 6 - count($relaInfo),
                ]);

                $albumInfo = array_combine(array_column($albumImfo, 'album_id'), $albumImfo);
                $albumInfo = array_slice($albumInfo, 0, 6 - count($relaInfo));
                $relaInfo = array_merge($relaInfo, $albumInfo);
            }
        }
        if (count($relaInfo) < 6) {
            if ($relaInfo && is_array($relaInfo)) {
                $album_ids = array_column($relaInfo, 'album_id');
                $notAlbumIds = array_merge($notAlbumIds, $album_ids);
            }
            $albumImfo = AlbumListModel::selectByWhere([
                'album_id[!]' => $notAlbumIds,
                'LIMIT' => 6 - count($relaInfo),
                'status' => AlbumListModel::STATS_LIST_PUBLIC_SHOW_MAP,
                'score[>=]' => AlbumListModel::SCORE_GOOD,
                'ORDER' => ['publish_time' => 'DESC']
            ]);
            $relaInfo = array_merge($relaInfo, $albumImfo);
        }
        $relaAlbumInfo = [];
        if ($relaInfo && is_array($relaInfo)) {
            $relaAlbumInfo = self::formatAlbums($relaInfo);
            foreach ($relaAlbumInfo as $key => &$val) {
                $val['statSign'] = basicStatSign::genStatSign(basicStatSign::ALBUM_DETAIL_PAGE_ALBUM_LIST, [
                    basicStatSign::EXTEND_KEY_OBJ_TYPE => BlockType::TYPE_WIKI_ALBUM,
                    basicStatSign::EXTEND_KEY_OBJ_ID => $val['album_info']['album_id'],
                    basicStatSign::EXTEND_KEY_POS => 'bottom',
                    basicStatSign::EXTEND_KEY_INDEX => $key,
                ], []);
            }
        }

        return $relaAlbumInfo;
    }

    /**
     * 根据清单id集合获取清单列表数据
     * @param $albumIds
     * @param array $where
     * @return array
     */
    public static function getAlbumListByIds($albumIds, array $where = []): array
    {
        $where['album_id'] = $albumIds;
        $data = AlbumListModel::selectByWhere($where) ?? [];
        if ($data) {
            return array_column($data, null, 'album_id');
        }

        return [];
    }

    public static function getAlbumOfTopic()
    {
        $info = [];
        $newRedis = new newCache(redisKeys::KEY_B_CACHE_ALBUM_TOPIC);
        $topicInfo = $newRedis->getCache();
        if ($topicInfo && is_array($topicInfo)) {
            $albumIds = array_column($topicInfo, 'album_id');
            $where['album_id'] = $albumIds;
            $where['status'] = AlbumListModel::STATS_LIST_PUBLIC_SHOW_MAP;
            $where['score[>=]'] = AlbumListModel::SCORE_GOOD;
            $albumInfo = AlbumListModel::selectByWhere($where);
            $albumList = self::formatAlbums($albumInfo);
            $albumList = array_combine(array_column($albumInfo, 'album_id'), $albumList);
            $albumCounters = AlbumCounter::getMulti($albumIds);
            foreach ($topicInfo as $key => &$val) {
                if ($albumList[$val['album_id']] && is_array($albumList[$val['album_id']])) {
                    $albumInfo = $albumList[$val['album_id']] ?: [];
                    $avatar_list = array_column(clsWiki::getRandUserCoverImg(3), 'cover_img');
                    $staSign = basicStatSign::genStatSign(basicStatSign::FINE_GOODS_PAGE_ALBUM_LIST, [
                        basicStatSign::EXTEND_KEY_OBJ_TYPE => BlockType::TYPE_WIKI_ALBUM,
                        basicStatSign::EXTEND_KEY_OBJ_ID => $val['album_id'],
                        basicStatSign::EXTEND_KEY_POS => 'order_second',
                        basicStatSign::EXTEND_KEY_INDEX => $key,
                    ], []);
                    $albumInfo['album_info']['first_tag'] = $val['package_name'] ?: '';
                    $albumInfo['album_info']['second_tag'] = "#" . $val['tag_name'] ?: '';
                    $albumInfo['album_info']['avatar_list'] = $avatar_list ?: [
                        "https://img.haohaozhu.cn/Pic-imageShow/sq_270/0004hn7b?iv=1&v=3",
                        "https://img.haohaozhu.cn/Pic-imageShow/sq_270/0004hn7p?iv=1&v=2",
                        "https://img.haohaozhu.cn/Pic-imageShow/sq_270/0004hneg?iv=1&v=3"];
                    $albumInfo['album_info']['joiner_num'] = $albumCounters[$val['album_id']]['read'] ?: 0;
                    $url = Hhzurl::getAlbumH5Link($val['album_id']);
                    $album_link = 'niceliving://webview/fullscreen?protego=' . urlencode(base64_encode(json_encode(['url' => $url, 'statSign' => urlencode(base64_encode($staSign))])));
                    $albumInfo['album_info']['album_link'] = $album_link;
                    $albumInfo['statSign'] = $staSign;
                    $info[] = $albumInfo;
                }

            }
        }

        return $info;

    }


    public static function setTopcCache()
    {
        $result = [];
        $TopicTags = AlbumRelateTagsModel::getTopicTags();
        if ($TopicTags && is_array($TopicTags)) {
            foreach ($TopicTags as $val) {
                $albumIds = AlbumRelateTagsModel::selectByWhere([
                    'package_name' => $val['package_name'],
                    'tag_name' => $val['tag_name'],
                    'status' => AlbumRelateTagsModel::STATUS_NORMAL,
                ], 'album_id');
                $info = AlbumListModel::getByWhere([
                    'album_id' => $albumIds,
                    'status' => AlbumListModel::STATS_LIST_PUBLIC_SHOW_MAP,
                    'score[>=]' => AlbumListModel::SCORE_GOOD,
                    'ORDER' => ['publish_time' => "DESC"]
                ], ['album_id', 'publish_time']);
                $result[$info['publish_time']] = [
                    'package_name' => $val['package_name'],
                    'tag_name' => $val['tag_name'],
                    'album_id' => $info['album_id'],
                    'publish_time' => $info['publish_time']
                ];
            }
            krsort($result);
            $cache = array_values($result);
            if ($cache && is_array($cache)) {
                $CacheStr = json_encode($cache);
                $newRedis = new newCache(redisKeys::KEY_B_CACHE_ALBUM_TOPIC);
                $newRedis->setCache($CacheStr);
            }
        }


    }

    /**
     * 检查用户是否有创建清单的权限（只有在白名单的用户,才可以创建）
     * 6.8 改为 仅支持普通用户、个人V认证、机构V认证用户创建
     * @param $uid
     * @return bool
     */
    public static function checkIsCanBuiltAlbum($uid): bool
    {
        $type = User::getUser($uid)['type'] ?? -100;
        if (in_array($type, [Member::USER_COMMON, Member::AUTH_USER_V, Member::AUTH_ORG_V])) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 关注线、个人主页动态使用
     * @param array $albumIds
     * @param $activeUid
     * @return array
     */
    public static function getDynamicAlbumByIds(array $albumIds, $activeUid = 0): array
    {
        $list = AlbumListModel::selectByWhere(['album_id' => $albumIds, 'status[!]' => [AlbumListModel::STATUS_DRAFT, AlbumListModel::STATUS_DELETE]],
            '*');
        $result = [];
        if ($list && is_array($list)) {
            $albumCounter = AlbumCounter::getMulti($albumIds);
            foreach ($list as $val) {
                $isOwner = ($activeUid && $val['uid'] == $activeUid) ? 1 : 0;
                if (in_array($val['status'], [AlbumListModel::STATUS_PRIVATE, AlbumListModel::STATUS_USER_PRIVATE]) && $isOwner == 0) {
                    Log::debug('过滤仅自己可见的清单', ['active_uid' => $activeUid, 'album_id' => $val['album_id'], 'uid' => $val['uid'], 'status' => $val['status']]);
                    continue;
                }
                $albumInfo = [
                    'album_id' => $val['album_id'],
                    'title' => $val['title'],
                    'desc' => $val['desc'],
                    'uid' => $val['uid'],
                    'status' => $val['status'],
                    'wiki_count' => (int)$val['wiki_count'],
                    'joiner_num' => $albumCounter[$val['album_id']]['read'] ?? 0,
                    'cover_img_url' => $val['cover_img'],
                    'album_link' => Hhzurl::getAlbumDetailNiceLivingLink($val['album_id']),
                    'quality' => $val['quality'],
                    'type' => BlockType::TYPE_WIKI_ALBUM,
                    'publish_time' => $val['publish_time'],
                ];
                $result[] = $albumInfo;
            }
        }
        return $result;
    }

    /**
     * 关注线获取清单数据
     * @param $albumIds
     * @param $uid
     * @return array
     */
    public static function getAlbumsForDynamic($albumIds, $uid)
    {
        $dbAlbumList = self::getDynamicAlbumByIds($albumIds, $uid);
        $result = [];
        if ($dbAlbumList && is_array($dbAlbumList)) {
            $albumList = array_combine(array_column($dbAlbumList, 'album_id'), $dbAlbumList);
            $uids = array_column($albumList, 'uid');
            $userList = User::getUsers($uids);

//            $followedList = Follow::isFollowedMulti($uid, $uids);
            $followStatus = Follow::FollowStatus($uid, $uids);

            // 收藏信息
            $favoritedList = Favorite::isFavoritedMulti($uid, $albumIds, mFavorite::TYPE_WIKI_ALBUM);
            //点赞信息
            $likedList = sLike::isLikedMulti($uid, $albumIds, 9);

            // 清单计数器
            $counterList = AlbumCounter::getMulti($albumIds);
            if ($albumList && is_array($albumList)) {
                foreach ($albumList as $album) {
                    if (!isset($userList[$album['uid']])) {
                        continue;
                    }

                    $result[$album['album_id']] = array(
//                        'user_info' => array_merge($userList[$album['album_info']['uid']], ['is_follow' => $followedList[$album['album_info']['uid']], 'is_follow_new' => $followStatus[$album['album_info']['uid']]]),
                        'user_info' => array_merge($userList[$album['uid']], ['is_follow_new' => $followStatus[$album['uid']]]),
                        'album_info' => [
                            'album_id' => $album['album_id'],
                            'publish_text' => "发布了好物清单", //卡片上方文字， 也不知道有啥用产品让加的
                            'title' => $album['title'],
                            'remark' => $album['desc'],
                            'cover_img_url' => $album['cover_img_url'],
                            'status' => $album['status'],
                            'wiki_count' => $album['wiki_count'],
                            'joiner_num' => $album['joiner_num'],
                            'quality' => $album['quality'],
                            'addtime' => $album['publish_time'],
                            'album_link' => $album['album_link'],
//                            'user_update_time' => $article_list[$article['aid']]['user_update_time'] ? : null,
//                            'publish_time' => $article_list[$article['aid']]['publish_time'],
                            'is_favorited' => (isset($favoritedList[$album['album_id']]) && $favoritedList[$album['album_id']]) ? 1 : 0,
                            'is_liked' => (isset($likedList[$album['album_id']]) && $likedList[$album['album_id']]) ? 1 : 0,
                        ],
                        'counter' => $counterList[$album['album_id']],
                    );
                }

                // 记录曝光日志
                if (HhzClient::isLogExpose()) {
                    ExposeLog::recordLog($albumIds);
                }
                $result = Sort::byArrayKey($albumIds, $result);
            }
        }
        return $result;
    }

    /**
     * 清单发布小贴士
     */
    public static function getTips(): array
    {
        return ['popup_title' => '清单发布小贴士',
            'popup_content' => "这样分享更容易被推荐：" . PHP_EOL .
                "1. 清单封面为不含logo、文字和价格信息的场景图；" . PHP_EOL .
                "2. 标题点明清单主题；" . PHP_EOL .
                "3. 商品与清单主题相符；" . PHP_EOL .
                "4. 商品大于5件；" . PHP_EOL .
                "5. 推荐语真实，不照抄广告语。" . PHP_EOL . PHP_EOL .
                "小tips📃：在清单详情页点击「清单封面」-「编辑」即可更换清单封面图。"
        ];
    }

    /**
     * 根据清单id，查询清单信息
     * @param array $albumIds 清单id
     * @param $filedGroup 使用场景
     * @return array
     */
    public static function getAlbumListByAlbumIds(array $albumIds, $filedGroup = FormatAlbumService::MASONRY_LIST)
    {
        $list = self::getAlbumListCache($albumIds);
        $list = FormatAlbumService::_formatAlbumList($list, $filedGroup);
        return $list;
    }

    /**
     * 获取清单基础信息缓存
     * @param array $albumIds
     * @return array
     */
    public static function getAlbumListCache(array $albumIds)
    {

        //实例化缓存
        $newRedis = new newCache(redisKeys::KEY_B_CACHE_ALBUM_LIST);
        [$cacheData, $noCacheKeys] = $newRedis->getCaches($albumIds);
        if ($noCacheKeys) {
            $albumList = AlbumListModel::selectByWhere([
                'status[!]' => AlbumListModel::STATUS_DELETE,
                'album_id' => $noCacheKeys
            ]);
            if($albumList){
                $albumList = array_column($albumList, null, 'album_id');

                $newRedis->setCaches($albumList);
                $result = $newRedis->getCaches($albumIds)[0] ?? [];
            }else{
                $result = $cacheData;
            }
        } else {
            $result = $cacheData;
        }
        return $result;
    }

    /**
     * 把商品添加至清单
     * @param $uid
     * @param $albumId
     * @param $wikiId
     * @param $wikiCount
     * @param $wikiIdsOld
     * @param $quality
     */
    public static function SaveAlbumWiki($uid , $albumId , $wikiId , $wikiCount , $wikiIdsOld , $quality)
    {
        if($albumId && $wikiId>0 && $wikiCount>0){
            $result = AlbumListModel::updateDataByWhere(['wiki_count'=>$wikiCount], ['album_id' => $albumId]);
            if($result) {
                $wikiData = [
                    'album_id' => $albumId,
                    'wiki_id' => $wikiId,
                    'uid' => $uid,
                    'sort' => 0, //由于之前添加商品 先后顺序是按照 1,2,3  这里新添加的商品要展示到第一个 所以这里的值=0
                    'status' => AlbumWikiListModel::STATUS_NORMAL,
                ];
                $res = AlbumWikiListModel::insertData($wikiData);
                if($res) {
                    //更新wiki_list 已关联
                    AlbumWikiListService::upWikiListData($uid, $wikiId);
                    //更新用户wiki清单
                    RelateWiki::changeUserWikiList($uid);
                    //更新用户成长值
                    $remarks = ['old_quality' =>  0, 'new_quality' => $quality, 'new_wiki_id' => array_merge($wikiIdsOld,[$wikiId]),'old_wiki_id' => $wikiIdsOld];
                    \Doraemon\amqp\CommunityQueue::insertQueue(\Doraemon\tools\Creator\GrowthConfig::MQ_QUEUE_URL, [
                        'event_name' => \Doraemon\tools\Creator\GrowthConfig::WIKI_GROWTH_WITH_ALBUM_LIST,
                        'obj_id' => $albumId,
                        'uid' => $uid,
                        'remarks' => json_encode($remarks, JSON_UNESCAPED_UNICODE),
                    ], \Doraemon\amqp\CommunityQueue::QUEUE_COMMUNITY);
                }
                }
            }
    }
}
